package com.feng.dt.service.impl;

import com.feng.common.exception.ErrorCode;
import com.feng.common.exception.ValidationException;
import com.feng.dt.model.entity.ScheduleJob;
import com.feng.dt.model.enums.Job_statusEnum;
import com.feng.dt.service.ScheduleJobService;
import com.feng.dt.util.ScheduleUtil;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author Lee
 */
@Service
public class ScheduleJobServiceImpl implements ScheduleJobService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ScheduleJobServiceImpl.class);

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private Scheduler scheduler;

    @Transactional
    @Override
    public void save(ScheduleJob scheduleJob) throws ValidationException{
        scheduleJob.fillDefaultValues();
        scheduleJob.setJobStatus(Job_statusEnum.PAUSE);
        try {
            em.persist(scheduleJob);
            ScheduleUtil.createJob(scheduler,scheduleJob);
        } catch (Exception e) {
            LOGGER.error("调度任务保存失败");
            throw new ValidationException(ErrorCode.SystemError,"调度任务保存失败");
        }
    }

    @Transactional
    @Override
    public void deleteJob(List<Integer> jobIds) throws ValidationException{
        try {
            jobIds.forEach(jobId -> em.remove(new ScheduleJob()));
        } catch (Exception e) {
            LOGGER.error("调度任务删除失败");
            throw new ValidationException(ErrorCode.SystemError,"调度任务删除失败");
        }
    }

    @Override
    public void deleteBatch(List<Integer> jobIds) throws ValidationException {
        jobIds.forEach(jobId -> ScheduleUtil.deleteJob(scheduler,jobId));
    }

    @Transactional
    @Override
    public void updateJob(ScheduleJob scheduleJob) throws ValidationException {
        em.merge(scheduleJob);
        ScheduleUtil.updateJob(scheduler,scheduleJob);
    }

    @Override
    public void pauseBatch(Integer jobId) throws ValidationException {
        ScheduleUtil.pauseJob(scheduler,jobId);
    }

    @Override
    public void resumeBatch(List<Integer> jobIds) throws ValidationException {
        jobIds.forEach(jobId -> ScheduleUtil.resumeJob(scheduler,jobId));
    }

    @Override
    public void startBatch(List<Integer> jobIds) throws ValidationException{
        jobIds.forEach(jobId -> ScheduleUtil.run(scheduler,jobId));
    }

    @Transactional
    @Override
    public void pauseJob(List<Integer> jobIds) {
            jobIds.forEach(jobId -> {
                try {
                    em.find(ScheduleJob.class, jobId).setJobStatus(Job_statusEnum.PAUSE);
                    jobIds.forEach(this::pauseBatch);
                } catch (Exception e) {
                    String msg = String.format("定时任务停止状态更新失败，任务id：[%s]", jobId);
                    LOGGER.error(msg);
                    throw new ValidationException(ErrorCode.SystemError, msg);
                }
            });
    }
}
